package com.xinyue.game.server.system;

import com.xinyue.network.codec.GameCodecFactory;
import com.xinyue.network.codec.GameMessageContext;
import com.xinyue.network.hamdlermapping.GameChannelContext;
import com.xinyue.network.message.ChannelHandShakeRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.Attribute;

@ChannelHandler.Sharable
public class DecodeHandler extends ChannelInboundHandlerAdapter {


    public DecodeHandler() {
        //添加系统消息
        GameCodecFactory.addMessageClass(ChannelHandShakeRequest.class);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            Attribute<byte[]> attr = ctx.channel().attr(GameChannelContext.CHANNEL_AES_ENCRYPT_KEY);
            GameMessageContext gameMessageContext = GameCodecFactory.readMessage(byteBuf, attr.get());
            ctx.fireChannelRead(gameMessageContext);
        }finally {
            byteBuf.release();
        }
    }
}
